package com.harmontronics.app.pedestal.bridge;

import android.webkit.JavascriptInterface;

import com.blankj.utilcode.util.LogUtils;
import com.harmontronics.app.pedestal.agent.WebActivity;
import com.harmontronics.app.pedestal.bridge.model.BaseBridge;
import com.harmontronics.app.pedestal.bridge.model.BridgeCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import wendu.dsbridge.CompletionHandler;

public class CameraBridge extends BaseBridge {

    private WebActivity activity;

    public CameraBridge(WebActivity activity) {
        this.activity = activity;
    }

    @JavascriptInterface
    public void scanCode(Object argsJson, CompletionHandler<String> handler) {
        LogUtils.d("CAMERA.scanCode");
        if (null == argsJson) {
            handler.complete(fail("参数不能为空", null));
            return;
        }

        try {
            JSONObject args = (JSONObject) argsJson;
            LogUtils.d("args: " + args.toString());
//            sourceType: ['album', 'camera'],
//            scanType: ['qrCode', 'barCode'],
            boolean useGallery = true;

            if (args.has("sourceType")) {
                JSONArray sourceType = args.getJSONArray("sourceType");
                List<String> sourceTypes = new ArrayList<>();
                if (sourceType.length() > 0) {
                    for (int i = 0; i < sourceType.length(); i++) {
                        sourceTypes.add(sourceType.getString(i));
                    }
                    useGallery = sourceTypes.contains("album");
                }
            }

            boolean scanQrCode = true;
            boolean scanBarCode = true;

            if (args.has("scanType")) {
                JSONArray sourceType = args.getJSONArray("scanType");
                List<String> sourceTypes = new ArrayList<>();
                if (sourceType.length() > 0) {
                    for (int i = 0; i < sourceType.length(); i++) {
                        sourceTypes.add(sourceType.getString(i));
                    }
                    scanQrCode = sourceTypes.contains("qrCode");
                    scanBarCode = sourceTypes.contains("barCode");
                }
            }

            int scanMode = 0;
            if (scanBarCode && !scanQrCode) {
                scanMode = 2;
            }

            if (scanQrCode && !scanBarCode) {
                scanMode = 1;
            }

            this.activity.scanCode(useGallery, scanMode, new BridgeCallback() {
                @Override
                public void onSuccess(Object result) {
                    handler.complete(success(result));
                }

                @Override
                public void onFail(String message) {
                    handler.complete(fail(message, null));
                }
            });
        } catch (Exception e) {
            handler.complete(fail(e.getMessage(), e));
        }
    }
}
